import*as e from"../../core/common/common.js";import*as t from"../../core/host/host.js";import*as s from"../../core/sdk/sdk.js";import*as n from"../bindings/bindings.js";import*as r from"../workspace/workspace.js";import*as i from"../../core/platform/platform.js";import*as o from"../text_utils/text_utils.js";import*as a from"../../core/i18n/i18n.js";import*as d from"../../ui/legacy/components/utils/utils.js";import*as l from"../breakpoints/breakpoints.js";import*as c from"../../ui/components/icon_button/icon_button.js";import*as h from"../../ui/legacy/legacy.js";import*as u from"../../core/root/root.js";const p={unableToReadFilesWithThis:"`PlatformFileSystem` cannot read files."},m=a.i18n.registerUIStrings("models/persistence/PlatformFileSystem.ts",p),g=a.i18n.getLocalizedString.bind(void 0,m);class f{pathInternal;typeInternal;constructor(e,t){this.pathInternal=e,this.typeInternal=t}getMetadata(e){return Promise.resolve(null)}initialFilePaths(){return[]}initialGitFolders(){return[]}path(){return this.pathInternal}embedderPath(){throw new Error("Not implemented")}type(){return this.typeInternal}async createFile(e,t){return Promise.resolve(null)}deleteFile(e){return Promise.resolve(!1)}requestFileBlob(e){return Promise.resolve(null)}async requestFileContent(e){return{content:null,error:g(p.unableToReadFilesWithThis),isEncoded:!1}}setFileContent(e,t,s){throw new Error("Not implemented")}renameFile(e,t,s){s(!1)}addExcludedFolder(e){}removeExcludedFolder(e){}fileSystemRemoved(){}isFileExcluded(e){return!1}excludedFolders(){return new Set}searchInPath(e,t){return Promise.resolve([])}indexContent(e){queueMicrotask((()=>{e.done()}))}mimeFromPath(e){throw new Error("Not implemented")}canExcludeFolder(e){return!1}contentType(e){throw new Error("Not implemented")}tooltipForURL(e){throw new Error("Not implemented")}supportsAutomapping(){throw new Error("Not implemented")}}var S=Object.freeze({__proto__:null,PlatformFileSystem:f});const y={fileSystemErrorS:"File system error: {PH1}",blobCouldNotBeLoaded:"Blob could not be loaded.",cantReadFileSS:"Can't read file: {PH1}: {PH2}",unknownErrorReadingFileS:"Unknown error reading file: {PH1}",linkedToS:"Linked to {PH1}"},P=a.i18n.registerUIStrings("models/persistence/IsolatedFileSystem.ts",y),F=a.i18n.getLocalizedString.bind(void 0,P);class w extends f{manager;embedderPathInternal;domFileSystem;excludedFoldersSetting;excludedFoldersInternal;excludedEmbedderFolders;initialFilePathsInternal;initialGitFoldersInternal;fileLocks;constructor(t,s,n,r,i){super(s,i),this.manager=t,this.embedderPathInternal=n,this.domFileSystem=r,this.excludedFoldersSetting=e.Settings.Settings.instance().createLocalSetting("workspaceExcludedFolders",{}),this.excludedFoldersInternal=new Set(this.excludedFoldersSetting.get()[s]||[]),this.excludedEmbedderFolders=[],this.initialFilePathsInternal=new Set,this.initialGitFoldersInternal=new Set,this.fileLocks=new Map}static async create(e,s,n,r,i,o){const a=t.InspectorFrontendHost.InspectorFrontendHostInstance.isolatedFileSystem(i,o);if(!a)return null;const d=new w(e,s,n,a,r);return d.initializeFilePaths().then((()=>d)).catch((e=>(console.error(e),null)))}static errorMessage(e){return F(y.fileSystemErrorS,{PH1:e.message})}serializedFileOperation(e,t){const s=Promise.resolve(this.fileLocks.get(e)).then((()=>t.call(null)));return this.fileLocks.set(e,s),s}getMetadata(t){let s;const n=new Promise((e=>{s=e}));return this.domFileSystem.root.getFile(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t),void 0,(function(e){e.getMetadata(s,r)}),r),n;function r(e){const n=w.errorMessage(e);console.error(n+" when getting file metadata '"+t),s(null)}}initialFilePaths(){return[...this.initialFilePathsInternal]}initialGitFolders(){return[...this.initialGitFoldersInternal]}embedderPath(){return this.embedderPathInternal}initializeFilePaths(){return new Promise((s=>{let n=1,r=0,o=1;const a=function(i){for(let s=0;s<i.length;++s){const d=i[s];if(d.isDirectory){if(d.fullPath.endsWith("/.git")){const t=d.fullPath.lastIndexOf("/"),s=e.ParsedURL.ParsedURL.substr(d.fullPath,1,t);this.initialGitFoldersInternal.add(e.ParsedURL.ParsedURL.rawPathToEncodedPathString(s))}if(this.isFileExcluded(e.ParsedURL.ParsedURL.concatenate(e.ParsedURL.ParsedURL.rawPathToEncodedPathString(d.fullPath),"/"))){const s=e.ParsedURL.ParsedURL.concatenate(this.path(),e.ParsedURL.ParsedURL.rawPathToEncodedPathString(d.fullPath));this.excludedEmbedderFolders.push(e.ParsedURL.ParsedURL.urlToRawPathString(s,t.Platform.isWin()));continue}++o,++n,this.requestEntries(d.fullPath,a)}else{if(this.isFileExcluded(e.ParsedURL.ParsedURL.rawPathToEncodedPathString(d.fullPath)))continue;++r,this.initialFilePathsInternal.add(e.ParsedURL.ParsedURL.rawPathToEncodedPathString(e.ParsedURL.ParsedURL.substr(d.fullPath,1)))}}0==--n&&(s(),""===this.type()&&t.userMetrics.workspacesNumberOfFiles(r,o))}.bind(this);this.requestEntries(i.DevToolsPath.EmptyRawPathString,a)}))}async createFoldersIfNotExist(e){let t=await new Promise((t=>this.domFileSystem.root.getDirectory(e,void 0,t,(()=>t(null)))));if(t)return t;const s=e.split("/");let n="";for(const e of s)if(n=n+"/"+e,t=await this.innerCreateFolderIfNeeded(n),!t)return null;return t}innerCreateFolderIfNeeded(e){return new Promise((t=>{this.domFileSystem.root.getDirectory(e,{create:!0},(e=>t(e)),(s=>{const n=w.errorMessage(s);console.error(n+" trying to create directory '"+e+"'"),t(null)}))}))}async createFile(t,s){const n=await this.createFoldersIfNotExist(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t));if(!n)return null;const r=await this.serializedFileOperation(t,function s(r,i){return new Promise((o=>{const a=e.ParsedURL.ParsedURL.concatenate(r,(i||"").toString());n.getFile(a,{create:!0,exclusive:!0},o,(e=>{if("InvalidModificationError"===e.name)return void o(s.call(this,r,i?i+1:1));const n=w.errorMessage(e);console.error(n+" when testing if file exists '"+this.path()+"/"+t+"/"+a+"'"),o(null)}))}))}.bind(this,s||"NewFile"));return r?e.ParsedURL.ParsedURL.rawPathToEncodedPathString(e.ParsedURL.ParsedURL.substr(r.fullPath,1)):null}deleteFile(t){let s;const n=new Promise((e=>{s=e}));return this.domFileSystem.root.getFile(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t),void 0,function(e){e.remove(r,i.bind(this))}.bind(this),i.bind(this)),n;function r(){s(!0)}function i(e){const n=w.errorMessage(e);console.error(n+" when deleting file '"+this.path()+"/"+t+"'"),s(!1)}}requestFileBlob(t){return new Promise((s=>{function n(e){if("NotFoundError"===e.name)return void s(null);const n=w.errorMessage(e);console.error(n+" when getting content for file '"+this.path()+"/"+t+"'"),s(null)}this.domFileSystem.root.getFile(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t),void 0,(e=>{e.file(s,n.bind(this))}),n.bind(this))}))}requestFileContent(e){return this.serializedFileOperation(e,(()=>this.innerRequestFileContent(e)))}async innerRequestFileContent(t){const s=await this.requestFileBlob(t);if(!s)return{content:null,error:F(y.blobCouldNotBeLoaded),isEncoded:!1};const n=new FileReader,r=e.ParsedURL.ParsedURL.extractExtension(t),i=k.has(r),o=new Promise((e=>{n.onloadend=e}));if(i?n.readAsBinaryString(s):n.readAsText(s),await o,n.error){const e=F(y.cantReadFileSS,{PH1:t,PH2:n.error.toString()});return console.error(e),{content:null,isEncoded:!1,error:e}}let a=null,d=null;try{a=n.result}catch(e){a=null,d=F(y.cantReadFileSS,{PH1:t,PH2:e.message})}return null==a?(d=d||F(y.unknownErrorReadingFileS,{PH1:t}),console.error(d),{content:null,isEncoded:!1,error:d}):{isEncoded:i,content:i?btoa(a):a}}async setFileContent(s,n,r){let i;t.userMetrics.actionTaken(t.UserMetrics.Action.FileSavedInWorkspace);function o(e){e.createWriter(a.bind(this),d.bind(this))}async function a(e){let t;e.onerror=d.bind(this),e.onwriteend=function(){e.onwriteend=i,e.truncate(t.size)},t=r?await(await fetch(`data:application/octet-stream;base64,${n}`)).blob():new Blob([n],{type:"text/plain"}),e.write(t)}function d(e){const t=w.errorMessage(e);console.error(t+" when setting content for file '"+this.path()+"/"+s+"'"),i(void 0)}this.serializedFileOperation(s,(()=>{const t=new Promise((e=>{i=e}));return this.domFileSystem.root.getFile(e.ParsedURL.ParsedURL.encodedPathToRawPathString(s),{create:!0},o.bind(this),d.bind(this)),t}))}renameFile(t,s,n){if(!(s=s?e.ParsedURL.ParsedURL.trim(s):s)||-1!==s.indexOf("/"))return void n(!1);let r,i;function o(e){i=e,i.getFile(s,void 0,a,d.bind(this))}function a(e){n(!1)}function d(e){"NotFoundError"===e.name?r.moveTo(i,s,l,c.bind(this)):n(!1)}function l(e){n(!0,e.name)}function c(e){const r=w.errorMessage(e);console.error(r+" when renaming file '"+this.path()+"/"+t+"' to '"+s+"'"),n(!1)}this.domFileSystem.root.getFile(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t),void 0,function(e){if(e.name===s)return void n(!1);r=e,r.getParent(o.bind(this),c.bind(this))}.bind(this),c.bind(this))}readDirectory(e,t){const s=e.createReader();let n=[];function r(s){const n=w.errorMessage(s);console.error(n+" when reading directory '"+e.fullPath+"'"),t([])}s.readEntries((function e(i){var o;i.length?(n=n.concat((o=i,Array.prototype.slice.call(o||[],0))),s.readEntries(e,r)):t(n.sort())}),r)}requestEntries(e,t){this.domFileSystem.root.getDirectory(e,void 0,function(e){this.readDirectory(e,t)}.bind(this),(function(s){const n=w.errorMessage(s);console.error(n+" when requesting entry '"+e+"'"),t([])}))}saveExcludedFolders(){const e=this.excludedFoldersSetting.get();e[this.path()]=[...this.excludedFoldersInternal],this.excludedFoldersSetting.set(e)}addExcludedFolder(e){this.excludedFoldersInternal.add(e),this.saveExcludedFolders(),this.manager.dispatchEventToListeners(M.ExcludedFolderAdded,e)}removeExcludedFolder(e){this.excludedFoldersInternal.delete(e),this.saveExcludedFolders(),this.manager.dispatchEventToListeners(M.ExcludedFolderRemoved,e)}fileSystemRemoved(){const e=this.excludedFoldersSetting.get();delete e[this.path()],this.excludedFoldersSetting.set(e)}isFileExcluded(t){if(this.excludedFoldersInternal.has(t))return!0;const s=this.manager.workspaceFolderExcludePatternSetting().asRegExp();return Boolean(s&&s.test(e.ParsedURL.ParsedURL.encodedPathToRawPathString(t)))}excludedFolders(){return this.excludedFoldersInternal}searchInPath(s,n){return new Promise((r=>{const i=this.manager.registerCallback((function(t){r(t.map((t=>e.ParsedURL.ParsedURL.rawPathToUrlString(t)))),n.incrementWorked(1)}));t.InspectorFrontendHost.InspectorFrontendHostInstance.searchInPath(i,this.embedderPathInternal,s)}))}indexContent(e){e.setTotalWork(1);const s=this.manager.registerProgress(e);t.InspectorFrontendHost.InspectorFrontendHostInstance.indexPath(s,this.embedderPathInternal,JSON.stringify(this.excludedEmbedderFolders))}mimeFromPath(t){return e.ResourceType.ResourceType.mimeFromURL(t)||"text/plain"}canExcludeFolder(e){return Boolean(e)&&"overrides"!==this.type()}contentType(t){const s=e.ParsedURL.ParsedURL.extractExtension(t);return v.has(s)?e.ResourceType.resourceTypes.Stylesheet:C.has(s)?e.ResourceType.resourceTypes.Document:U.has(s)?e.ResourceType.resourceTypes.Image:I.has(s)?e.ResourceType.resourceTypes.Script:k.has(s)?e.ResourceType.resourceTypes.Other:e.ResourceType.resourceTypes.Document}tooltipForURL(s){const n=i.StringUtilities.trimMiddle(e.ParsedURL.ParsedURL.urlToRawPathString(s,t.Platform.isWin()),150);return F(y.linkedToS,{PH1:n})}supportsAutomapping(){return"overrides"!==this.type()}}const v=new Set(["css","scss","sass","less"]),C=new Set(["htm","html","asp","aspx","phtml","jsp"]),I=new Set(["asp","aspx","c","cc","cljs","coffee","cpp","cs","dart","java","js","jsp","jsx","h","m","mjs","mm","py","sh","ts","tsx","ls"]),U=new Set(["jpeg","jpg","svg","gif","webp","png","ico","tiff","tif","bmp"]),k=new Set(["cmd","com","exe","a","ar","iso","tar","bz2","gz","lz","lzma","z","7z","apk","arc","cab","dmg","jar","pak","rar","zip","3gp","aac","aiff","flac","m4a","mmf","mp3","ogg","oga","raw","sln","wav","wma","webm","mkv","flv","vob","ogv","gifv","avi","mov","qt","mp4","m4p","m4v","mpg","mpeg","jpeg","jpg","gif","webp","png","ico","tiff","tif","bmp"]);var R=Object.freeze({__proto__:null,IsolatedFileSystem:w,BinaryExtensions:k});const x={unableToAddFilesystemS:"Unable to add filesystem: {PH1}"},L=a.i18n.registerUIStrings("models/persistence/IsolatedFileSystemManager.ts",x),b=a.i18n.getLocalizedString.bind(void 0,L);let E;class T extends e.ObjectWrapper.ObjectWrapper{fileSystemsInternal;callbacks;progresses;workspaceFolderExcludePatternSettingInternal;fileSystemRequestResolve;fileSystemsLoadedPromise;constructor(){super(),this.fileSystemsInternal=new Map,this.callbacks=new Map,this.progresses=new Map,t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.FileSystemRemoved,this.onFileSystemRemoved,this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.FileSystemAdded,(e=>{this.onFileSystemAdded(e)}),this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.FileSystemFilesChangedAddedRemoved,this.onFileSystemFilesChanged,this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.IndexingTotalWorkCalculated,this.onIndexingTotalWorkCalculated,this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.IndexingWorked,this.onIndexingWorked,this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.IndexingDone,this.onIndexingDone,this),t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.SearchCompleted,this.onSearchCompleted,this);const s=["/Thumbs.db$","/ehthumbs.db$","/Desktop.ini$","/\\$RECYCLE.BIN/"],n=["/\\.DS_Store$","/\\.Trashes$","/\\.Spotlight-V100$","/\\.AppleDouble$","/\\.LSOverride$","/Icon$","/\\._.*$"],r=["/.*~$"];let i=["/node_modules/","/bower_components/","/\\.devtools","/\\.git/","/\\.sass-cache/","/\\.hg/","/\\.idea/","/\\.svn/","/\\.cache/","/\\.project/"];i=t.Platform.isWin()?i.concat(s):t.Platform.isMac()?i.concat(n):i.concat(r);const o=i.join("|");this.workspaceFolderExcludePatternSettingInternal=e.Settings.Settings.instance().createRegExpSetting("workspaceFolderExcludePattern",o,t.Platform.isWin()?"i":""),this.fileSystemRequestResolve=null,this.fileSystemsLoadedPromise=this.requestFileSystems()}static instance(e={forceNew:null}){const{forceNew:t}=e;return E&&!t||(E=new T),E}static removeInstance(){E=null}requestFileSystems(){let e;const s=new Promise((t=>{e=t}));return t.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(t.InspectorFrontendHostAPI.Events.FileSystemsLoaded,(function(e){const t=e.data,s=[];for(let e=0;e<t.length;++e)s.push(this.innerAddFileSystem(t[e],!1));Promise.all(s).then(n)}),this),t.InspectorFrontendHost.InspectorFrontendHostInstance.requestFileSystems(),s;function n(t){e(t.filter((e=>Boolean(e))))}}addFileSystem(e){return t.userMetrics.actionTaken("overrides"===e?t.UserMetrics.Action.AddFileSystemForOverrides:t.UserMetrics.Action.AddFileSystemToWorkspace),new Promise((s=>{this.fileSystemRequestResolve=s,t.InspectorFrontendHost.InspectorFrontendHostInstance.addFileSystem(e||"")}))}removeFileSystem(e){t.userMetrics.actionTaken("overrides"===e.type()?t.UserMetrics.Action.RemoveFileSystemForOverrides:t.UserMetrics.Action.RemoveFileSystemFromWorkspace),t.InspectorFrontendHost.InspectorFrontendHostInstance.removeFileSystem(e.embedderPath())}waitForFileSystems(){return this.fileSystemsLoadedPromise}innerAddFileSystem(t,s){const n=t.fileSystemPath,r=e.ParsedURL.ParsedURL.rawPathToUrlString(t.fileSystemPath);return w.create(this,r,n,t.type,t.fileSystemName,t.rootURL).then(function(e){if(!e)return null;this.fileSystemsInternal.set(r,e),s&&this.dispatchEventToListeners(M.FileSystemAdded,e);return e}.bind(this))}addPlatformFileSystem(e,t){this.fileSystemsInternal.set(e,t),this.dispatchEventToListeners(M.FileSystemAdded,t)}onFileSystemAdded(t){const{errorMessage:s,fileSystem:n}=t.data;if(s){if("<selection cancelled>"!==s&&e.Console.Console.instance().error(b(x.unableToAddFilesystemS,{PH1:s})),!this.fileSystemRequestResolve)return;this.fileSystemRequestResolve.call(null,null),this.fileSystemRequestResolve=null}else n&&this.innerAddFileSystem(n,!0).then((e=>{this.fileSystemRequestResolve&&(this.fileSystemRequestResolve.call(null,e),this.fileSystemRequestResolve=null)}))}onFileSystemRemoved(t){const s=t.data,n=e.ParsedURL.ParsedURL.rawPathToUrlString(s),r=this.fileSystemsInternal.get(n);r&&(this.fileSystemsInternal.delete(n),r.fileSystemRemoved(),this.dispatchEventToListeners(M.FileSystemRemoved,r))}onFileSystemFilesChanged(t){const s={changed:n.call(this,t.data.changed),added:n.call(this,t.data.added),removed:n.call(this,t.data.removed)};function n(t){const s=new i.MapUtilities.Multimap;for(const n of t){const t=e.ParsedURL.ParsedURL.rawPathToUrlString(n);for(const r of this.fileSystemsInternal.keys()){const i=this.fileSystemsInternal.get(r);if(i&&i.isFileExcluded(e.ParsedURL.ParsedURL.rawPathToEncodedPathString(n)))continue;const o=r.endsWith("/")?r:r+"/";t.startsWith(o)&&s.set(r,t)}}return s}this.dispatchEventToListeners(M.FileSystemFilesChanged,s)}fileSystems(){return[...this.fileSystemsInternal.values()]}fileSystem(e){return this.fileSystemsInternal.get(e)||null}workspaceFolderExcludePatternSetting(){return this.workspaceFolderExcludePatternSettingInternal}registerCallback(e){const t=++j;return this.callbacks.set(t,e),t}registerProgress(e){const t=++j;return this.progresses.set(t,e),t}onIndexingTotalWorkCalculated(e){const{requestId:t,totalWork:s}=e.data,n=this.progresses.get(t);n&&n.setTotalWork(s)}onIndexingWorked(e){const{requestId:s,worked:n}=e.data,r=this.progresses.get(s);r&&(r.incrementWorked(n),r.isCanceled()&&(t.InspectorFrontendHost.InspectorFrontendHostInstance.stopIndexing(s),this.onIndexingDone(e)))}onIndexingDone(e){const{requestId:t}=e.data,s=this.progresses.get(t);s&&(s.done(),this.progresses.delete(t))}onSearchCompleted(e){const{requestId:t,files:s}=e.data,n=this.callbacks.get(t);n&&(n.call(null,s),this.callbacks.delete(t))}}var M;!function(e){e.FileSystemAdded="FileSystemAdded",e.FileSystemRemoved="FileSystemRemoved",e.FileSystemFilesChanged="FileSystemFilesChanged",e.ExcludedFolderAdded="ExcludedFolderAdded",e.ExcludedFolderRemoved="ExcludedFolderRemoved"}(M||(M={}));let j=0;var W=Object.freeze({__proto__:null,IsolatedFileSystemManager:T,get Events(){return M}});class A{isolatedFileSystemManager;workspace;eventListeners;boundFileSystems;constructor(e,t){this.isolatedFileSystemManager=e,this.workspace=t,this.eventListeners=[this.isolatedFileSystemManager.addEventListener(M.FileSystemAdded,this.onFileSystemAdded,this),this.isolatedFileSystemManager.addEventListener(M.FileSystemRemoved,this.onFileSystemRemoved,this),this.isolatedFileSystemManager.addEventListener(M.FileSystemFilesChanged,this.fileSystemFilesChanged,this)],this.boundFileSystems=new Map,this.isolatedFileSystemManager.waitForFileSystems().then(this.onFileSystemsLoaded.bind(this))}static projectId(e){return e}static relativePath(t){const s=t.project().fileSystemBaseURL;return e.ParsedURL.ParsedURL.split(e.ParsedURL.ParsedURL.sliceUrlToEncodedPathString(t.url(),s.length),"/")}static tooltipForUISourceCode(e){return e.project().fileSystemInternal.tooltipForURL(e.url())}static fileSystemType(e){return e.fileSystemInternal.type()}static fileSystemSupportsAutomapping(e){return e.fileSystemInternal.supportsAutomapping()}static completeURL(t,s){const n=t;return e.ParsedURL.ParsedURL.concatenate(n.fileSystemBaseURL,s)}static fileSystemPath(e){return e}fileSystemManager(){return this.isolatedFileSystemManager}onFileSystemsLoaded(e){for(const t of e)this.addFileSystem(t)}onFileSystemAdded(e){const t=e.data;this.addFileSystem(t)}addFileSystem(e){const t=new B(this,e,this.workspace);this.boundFileSystems.set(e.path(),t)}onFileSystemRemoved(e){const t=e.data,s=this.boundFileSystems.get(t.path());s&&s.dispose(),this.boundFileSystems.delete(t.path())}fileSystemFilesChanged(e){const t=e.data;for(const e of t.changed.keysArray()){const s=this.boundFileSystems.get(e);s&&t.changed.get(e).forEach((e=>s.fileChanged(e)))}for(const e of t.added.keysArray()){const s=this.boundFileSystems.get(e);s&&t.added.get(e).forEach((e=>s.fileChanged(e)))}for(const e of t.removed.keysArray()){const s=this.boundFileSystems.get(e);s&&t.removed.get(e).forEach((e=>s.removeUISourceCode(e)))}}dispose(){e.EventTarget.removeEventListeners(this.eventListeners);for(const e of this.boundFileSystems.values())e.dispose(),this.boundFileSystems.delete(e.fileSystemInternal.path())}}class B extends r.Workspace.ProjectStore{fileSystemInternal;fileSystemBaseURL;fileSystemParentURL;fileSystemWorkspaceBinding;fileSystemPathInternal;creatingFilesGuard;constructor(t,s,n){const i=s.path(),o=A.projectId(i);console.assert(!n.project(o));const a=i.substr(i.lastIndexOf("/")+1);super(n,o,r.Workspace.projectTypes.FileSystem,a),this.fileSystemInternal=s,this.fileSystemBaseURL=e.ParsedURL.ParsedURL.concatenate(this.fileSystemInternal.path(),"/"),this.fileSystemParentURL=e.ParsedURL.ParsedURL.substr(this.fileSystemBaseURL,0,i.lastIndexOf("/")+1),this.fileSystemWorkspaceBinding=t,this.fileSystemPathInternal=i,this.creatingFilesGuard=new Set,n.addProject(this),this.populate()}fileSystemPath(){return this.fileSystemPathInternal}fileSystem(){return this.fileSystemInternal}mimeType(e){return this.fileSystemInternal.mimeFromPath(e.url())}initialGitFolders(){return this.fileSystemInternal.initialGitFolders().map((t=>e.ParsedURL.ParsedURL.concatenate(this.fileSystemPathInternal,"/",t)))}filePathForUISourceCode(t){return e.ParsedURL.ParsedURL.sliceUrlToEncodedPathString(t.url(),this.fileSystemPathInternal.length)}isServiceProject(){return!1}requestMetadata(e){const t=H.get(e);if(t)return t;const s=this.filePathForUISourceCode(e),n=this.fileSystemInternal.getMetadata(s).then((function(e){if(!e)return null;return new r.UISourceCode.UISourceCodeMetadata(e.modificationTime,e.size)}));return H.set(e,n),n}requestFileBlob(e){return this.fileSystemInternal.requestFileBlob(this.filePathForUISourceCode(e))}requestFileContent(e){const t=this.filePathForUISourceCode(e);return this.fileSystemInternal.requestFileContent(t)}canSetFileContent(){return!0}async setFileContent(e,t,s){const n=this.filePathForUISourceCode(e);await this.fileSystemInternal.setFileContent(n,t,s)}fullDisplayName(e){const t=e.project().fileSystemParentURL;return e.url().substring(t.length)}canRename(){return!0}rename(t,s,n){if(s===t.name())return void n(!0,t.name(),t.url(),t.contentType());let r=this.filePathForUISourceCode(t);this.fileSystemInternal.renameFile(r,s,function(s,i){if(!s||!i)return void n(!1,i);console.assert(Boolean(i));const o=r.lastIndexOf("/"),a=e.ParsedURL.ParsedURL.substr(r,0,o);r=e.ParsedURL.ParsedURL.encodedFromParentPathAndName(a,i),r=e.ParsedURL.ParsedURL.substr(r,1);const d=e.ParsedURL.ParsedURL.concatenate(this.fileSystemBaseURL,r),l=this.fileSystemInternal.contentType(i);this.renameUISourceCode(t,i),n(!0,i,d,l)}.bind(this))}async searchInFileContent(e,t,s,n){const r=this.filePathForUISourceCode(e),{content:i}=await this.fileSystemInternal.requestFileContent(r);return i?o.TextUtils.performSearchInContent(i,t,s,n):[]}async findFilesMatchingSearchRequest(e,t,s){let n=t;const r=e.queries().slice();r.length||r.push(""),s.setTotalWork(r.length);for(const t of r){const r=await this.fileSystemInternal.searchInPath(e.isRegex()?"":t,s);r.sort(i.StringUtilities.naturalOrderComparator),n=i.ArrayUtilities.intersectOrdered(n,r,i.StringUtilities.naturalOrderComparator),s.incrementWorked(1)}return s.done(),n}indexContent(e){this.fileSystemInternal.indexContent(e)}populate(){const e=this.fileSystemInternal.initialFilePaths();if(0===e.length)return;const s=performance.now();(function n(r){const i=Math.min(r+1e3,e.length);for(let t=r;t<i;++t)this.addFile(e[t]);i<e.length?window.setTimeout(n.bind(this,i),100):"filesystem"===this.type()&&t.userMetrics.workspacesPopulated(performance.now()-s)}).call(this,0)}excludeFolder(t){let s=e.ParsedURL.ParsedURL.sliceUrlToEncodedPathString(t,this.fileSystemBaseURL.length);s.startsWith("/")||(s=e.ParsedURL.ParsedURL.prepend("/",s)),s.endsWith("/")||(s=e.ParsedURL.ParsedURL.concatenate(s,"/")),this.fileSystemInternal.addExcludedFolder(s);for(const e of this.uiSourceCodes())e.url().startsWith(t)&&this.removeUISourceCode(e.url())}canExcludeFolder(e){return this.fileSystemInternal.canExcludeFolder(e)}canCreateFile(){return!0}async createFile(e,t,s,n){const r=this.fileSystemPathInternal+e+(e.endsWith("/")?"":"/")+t;this.creatingFilesGuard.add(r);const i=await this.fileSystemInternal.createFile(e,t);if(!i)return null;const o=this.addFile(i);return o.setContent(s,Boolean(n)),this.creatingFilesGuard.delete(r),o}deleteFile(e){const t=this.filePathForUISourceCode(e);this.fileSystemInternal.deleteFile(t).then((t=>{t&&this.removeUISourceCode(e.url())}))}remove(){this.fileSystemWorkspaceBinding.isolatedFileSystemManager.removeFileSystem(this.fileSystemInternal)}addFile(t){const s=this.fileSystemInternal.contentType(t),n=this.createUISourceCode(e.ParsedURL.ParsedURL.concatenate(this.fileSystemBaseURL,t),s);return this.addUISourceCode(n),n}fileChanged(e){if(this.creatingFilesGuard.has(e))return;const t=this.uiSourceCodeForURL(e);if(t)H.delete(t),t.checkContentUpdated();else{const t=this.fileSystemInternal.contentType(e);this.addUISourceCode(this.createUISourceCode(e,t))}}tooltipForURL(e){return this.fileSystemInternal.tooltipForURL(e)}dispose(){this.removeProject()}}const H=new WeakMap;var N=Object.freeze({__proto__:null,FileSystemWorkspaceBinding:A,FileSystem:B});let O;class q extends e.ObjectWrapper.ObjectWrapper{bindings;originalResponseContentPromises;savingForOverrides;savingSymbol;enabledSetting;workspace;networkUISourceCodeForEncodedPath;interceptionHandlerBound;updateInterceptionThrottler;projectInternal;activeProject;activeInternal;enabled;eventDescriptors;#e=new Map;#t=new WeakMap;#s;#n;constructor(t){super(),this.bindings=new WeakMap,this.originalResponseContentPromises=new WeakMap,this.savingForOverrides=new WeakSet,this.savingSymbol=Symbol("SavingForOverrides"),this.enabledSetting=e.Settings.Settings.instance().moduleSetting("persistenceNetworkOverridesEnabled"),this.enabledSetting.addChangeListener(this.enabledChanged,this),this.workspace=t,this.networkUISourceCodeForEncodedPath=new Map,this.interceptionHandlerBound=this.interceptionHandler.bind(this),this.updateInterceptionThrottler=new e.Throttler.Throttler(50),this.#s=new e.Throttler.Throttler(50),this.#n=new Set,this.projectInternal=null,this.activeProject=null,this.activeInternal=!1,this.enabled=!1,this.workspace.addEventListener(r.Workspace.Events.ProjectAdded,(e=>{this.onProjectAdded(e.data)})),this.workspace.addEventListener(r.Workspace.Events.ProjectRemoved,(e=>{this.onProjectRemoved(e.data)})),se.instance().addNetworkInterceptor(this.canHandleNetworkUISourceCode.bind(this)),l.BreakpointManager.BreakpointManager.instance().addUpdateBindingsCallback(this.networkUISourceCodeAdded.bind(this)),this.eventDescriptors=[],this.enabledChanged(),s.TargetManager.TargetManager.instance().observeTargets(this)}targetAdded(){this.updateActiveProject()}targetRemoved(){this.updateActiveProject()}static instance(e={forceNew:null,workspace:null}){const{forceNew:t,workspace:s}=e;if(!O||t){if(!s)throw new Error("Missing workspace for NetworkPersistenceManager");O=new q(s)}return O}active(){return this.activeInternal}project(){return this.projectInternal}originalContentForUISourceCode(e){const t=this.bindings.get(e);if(!t)return null;const s=t.fileSystem;return this.originalResponseContentPromises.get(s)||null}async enabledChanged(){this.enabled!==this.enabledSetting.get()&&(this.enabled=this.enabledSetting.get(),this.enabled?(t.userMetrics.actionTaken(t.UserMetrics.Action.PersistenceNetworkOverridesEnabled),this.eventDescriptors=[r.Workspace.WorkspaceImpl.instance().addEventListener(r.Workspace.Events.UISourceCodeRenamed,(e=>{this.uiSourceCodeRenamedListener(e)})),r.Workspace.WorkspaceImpl.instance().addEventListener(r.Workspace.Events.UISourceCodeAdded,(e=>{this.uiSourceCodeAdded(e)})),r.Workspace.WorkspaceImpl.instance().addEventListener(r.Workspace.Events.UISourceCodeRemoved,(e=>{this.uiSourceCodeRemovedListener(e)})),r.Workspace.WorkspaceImpl.instance().addEventListener(r.Workspace.Events.WorkingCopyCommitted,(e=>this.onUISourceCodeWorkingCopyCommitted(e.data.uiSourceCode)))],await this.updateActiveProject()):(t.userMetrics.actionTaken(t.UserMetrics.Action.PersistenceNetworkOverridesDisabled),e.EventTarget.removeEventListeners(this.eventDescriptors),await this.updateActiveProject()))}async uiSourceCodeRenamedListener(e){const t=e.data.uiSourceCode;await this.onUISourceCodeRemoved(t),await this.onUISourceCodeAdded(t)}async uiSourceCodeRemovedListener(e){await this.onUISourceCodeRemoved(e.data)}async uiSourceCodeAdded(e){await this.onUISourceCodeAdded(e.data)}async updateActiveProject(){const e=this.activeInternal;if(this.activeInternal=Boolean(this.enabledSetting.get()&&s.TargetManager.TargetManager.instance().rootTarget()&&this.projectInternal),this.activeInternal!==e){if(this.activeInternal&&this.projectInternal){await Promise.all([...this.projectInternal.uiSourceCodes()].map((e=>this.filesystemUISourceCodeAdded(e))));const e=this.workspace.projectsForType(r.Workspace.projectTypes.Network);for(const t of e)await Promise.all([...t.uiSourceCodes()].map((e=>this.networkUISourceCodeAdded(e))))}else this.projectInternal&&(await Promise.all([...this.projectInternal.uiSourceCodes()].map((e=>this.filesystemUISourceCodeRemoved(e)))),this.networkUISourceCodeForEncodedPath.clear());se.instance().refreshAutomapping()}}encodedPathFromUrl(t,s){return e.ParsedURL.ParsedURL.rawPathToEncodedPathString(this.rawPathFromUrl(t,s))}rawPathFromUrl(t,s){if(!this.activeInternal&&!s||!this.projectInternal)return i.DevToolsPath.EmptyRawPathString;let n=e.ParsedURL.ParsedURL.urlWithoutHash(t.replace(/^https?:\/\//,""));n.endsWith("/")&&-1===n.indexOf("?")&&(n=e.ParsedURL.ParsedURL.concatenate(n,"index.html"));let r=q.encodeEncodedPathToLocalPathParts(n);const o=A.fileSystemPath(this.projectInternal.id()),a=r.join("/");if(o.length+a.length>200){const t=r[0],s=r[r.length-1],o=s?s.substr(0,10)+"-":"",d=e.ParsedURL.ParsedURL.extractExtension(n),l=d?"."+d.substr(0,10):"";r=[t,"longurls",o+i.StringUtilities.hashCode(a).toString(16)+l]}return e.ParsedURL.ParsedURL.join(r,"/")}static encodeEncodedPathToLocalPathParts(e){const s=[];for(const n of this.#r(e)){if(!n)continue;let e=encodeURI(n).replace(/[\/\*]/g,(e=>"%"+e[0].charCodeAt(0).toString(16).toUpperCase()));if(t.Platform.isWin()){e=e.replace(/[:\?]/g,(e=>"%"+e[0].charCodeAt(0).toString(16).toUpperCase())),D.has(e.toLowerCase())&&(e=e.split("").map((e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())).join(""));"."===e.charAt(e.length-1)&&(e=e.substr(0,e.length-1)+"%2E")}s.push(e)}return s}static#r(t){const s=(t=e.ParsedURL.ParsedURL.urlWithoutHash(t)).indexOf("?");if(-1===s)return t.split("/");if(0===s)return[t];const n=t.substr(s),r=t.substr(0,t.length-n.length).split("/");return r[r.length-1]+=n,r}fileUrlFromNetworkUrl(t,s){return this.projectInternal?e.ParsedURL.ParsedURL.concatenate(this.projectInternal.fileSystemPath(),"/",this.encodedPathFromUrl(t,s)):i.DevToolsPath.EmptyUrlString}getHeadersUISourceCodeFromUrl(t){const s=this.fileUrlFromNetworkUrl(t,!0),n=e.ParsedURL.ParsedURL.substring(s,0,s.lastIndexOf("/")),i=e.ParsedURL.ParsedURL.concatenate(n,"/",_);return r.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(i)}async getOrCreateHeadersUISourceCodeFromUrl(s){let n=this.getHeadersUISourceCodeFromUrl(s);if(!n&&this.projectInternal){const r=this.encodedPathFromUrl(s,!0),i=e.ParsedURL.ParsedURL.substring(r,0,r.lastIndexOf("/"));n=await this.projectInternal.createFile(i,_,""),t.userMetrics.actionTaken(t.UserMetrics.Action.HeaderOverrideFileCreated)}return n}decodeLocalPathToUrlPath(e){try{return unescape(e)}catch(e){console.error(e)}return e}async#i(e){const t=this.bindings.get(e);if(t){const e=this.#o(t.network);await e.run(this.#a.bind(this,t))}}async#d(e){const t=this.bindings.get(e);t&&await this.#a(t)}#a(e){return this.bindings.delete(e.network),this.bindings.delete(e.fileSystem),se.instance().removeBinding(e)}async#l(e,t){const s=this.#o(e);await s.run((async()=>{const s=this.bindings.get(e);if(s){const{network:n,fileSystem:r}=s;if(e===n&&t===r)return;await this.#d(e),await this.#d(t)}await this.#c(e,t)}))}#o(t){let s=this.#t.get(t);return s||(s=new e.Mutex.Mutex,this.#t.set(t,s)),s}async#c(e,t){const s=new ue(e,t);this.bindings.set(e,s),this.bindings.set(t,s),await se.instance().addBinding(s);const n=this.savingForOverrides.has(e)?e:t,{content:r,isEncoded:i}=await n.requestContent();se.instance().syncContent(n,r||"",i)}onUISourceCodeWorkingCopyCommitted(e){this.saveUISourceCodeForOverrides(e),this.updateInterceptionPatterns()}canSaveUISourceCodeForOverrides(e){return this.activeInternal&&e.project().type()===r.Workspace.projectTypes.Network&&!this.bindings.has(e)&&!this.savingForOverrides.has(e)}async saveUISourceCodeForOverrides(t){if(!this.canSaveUISourceCodeForOverrides(t))return;this.savingForOverrides.add(t);let s=this.encodedPathFromUrl(t.url());const{content:n,isEncoded:r}=await t.requestContent(),i=s.lastIndexOf("/"),o=e.ParsedURL.ParsedURL.substring(s,i+1),a=e.ParsedURL.ParsedURL.encodedPathToRawPathString(o);s=e.ParsedURL.ParsedURL.substr(s,0,i),this.projectInternal&&await this.projectInternal.createFile(s,a,n??"",r),this.fileCreatedForTest(s,a),this.savingForOverrides.delete(t)}fileCreatedForTest(e,t){}patternForFileSystemUISourceCode(e){const t=A.relativePath(e);if(t.length<2)return"";if("longurls"===t[1]&&2!==t.length)return"file:"===t[0]?"file:///*":"http?://"+t[0]+"/*";const s=this.decodeLocalPathToUrlPath(this.decodeLocalPathToUrlPath(t.join("/")));return s.startsWith("file:/")?"file:///"+s.substring("file:/".length):"http?://"+s}async onUISourceCodeAdded(e){await this.networkUISourceCodeAdded(e),await this.filesystemUISourceCodeAdded(e)}canHandleNetworkUISourceCode(e){return this.activeInternal&&!e.url().startsWith("snippet://")}async networkUISourceCodeAdded(t){if(t.project().type()!==r.Workspace.projectTypes.Network||!this.canHandleNetworkUISourceCode(t))return;const s=e.ParsedURL.ParsedURL.urlWithoutHash(t.url());this.networkUISourceCodeForEncodedPath.set(this.encodedPathFromUrl(s),t);const n=this.projectInternal.uiSourceCodeForURL(this.fileUrlFromNetworkUrl(s));n&&await this.#l(t,n),this.#h(t)}async filesystemUISourceCodeAdded(t){if(!this.activeInternal||t.project()!==this.projectInternal)return;this.updateInterceptionPatterns();const s=A.relativePath(t),n=this.networkUISourceCodeForEncodedPath.get(e.ParsedURL.ParsedURL.join(s,"/"));n&&await this.#l(n,t)}async#u(e){const t=(await e.requestContent()).content||"[]";let s=[];try{if(s=JSON.parse(t),!s.every($))throw"Type mismatch after parsing"}catch(t){return console.error("Failed to parse",e.url(),"for locally overriding headers."),[]}return s}#p(e){const t=this.decodeLocalPathToUrlPath(e);return{singlyDecodedPath:t,decodedPath:this.decodeLocalPathToUrlPath(t)}}async generateHeaderPatterns(t){const s=await this.#u(t),n=A.relativePath(t),r=e.ParsedURL.ParsedURL.slice(e.ParsedURL.ParsedURL.join(n,"/"),0,-_.length),{singlyDecodedPath:i,decodedPath:o}=this.#p(r);let a;return a=n.length>2&&"longurls"===n[1]&&s.length?this.#m(o,s,n[0]):o.startsWith("file:/")?this.#g(e.ParsedURL.ParsedURL.substring(o,"file:/".length),s):this.#f(o,s),{...a,path:i}}#f(e,t){const s=new Set,n=[];for(const r of t){s.add("http?://"+e+r.applyTo),""===e&&(s.add("file:///"+r.applyTo),n.push({applyToRegex:new RegExp("^file:///"+G(e+r.applyTo)+"$"),headers:r.headers}));const{head:t,tail:i}=V(r.applyTo);i?(s.add("http?://"+e+t),n.push({applyToRegex:new RegExp(`^${G(e+t)}(${G(i)})?$`),headers:r.headers})):n.push({applyToRegex:new RegExp(`^${G(e+r.applyTo)}$`),headers:r.headers})}return{headerPatterns:s,overridesWithRegex:n}}#g(e,t){const s=new Set,n=[];for(const r of t)s.add("file:///"+e+r.applyTo),n.push({applyToRegex:new RegExp(`^file:/${G(e+r.applyTo)}$`),headers:r.headers});return{headerPatterns:s,overridesWithRegex:n}}#m(t,s,n){const r=new Set;let{decodedPath:i}=this.#p(e.ParsedURL.ParsedURL.concatenate(n,"/*"));const o=t.startsWith("file:/");o&&(t=e.ParsedURL.ParsedURL.substring(t,"file:/".length),i=e.ParsedURL.ParsedURL.substring(i,"file:/".length)),r.add((o?"file:///":"http?://")+i);const a=[];for(const e of s)a.push({applyToRegex:new RegExp(`^${o?"file:/":""}${G(t+e.applyTo)}$`),headers:e.headers});return{headerPatterns:r,overridesWithRegex:a}}async updateInterceptionPatternsForTests(){await this.#S()}updateInterceptionPatterns(){this.updateInterceptionThrottler.schedule(this.#S.bind(this))}async#S(){if(this.#e.clear(),!this.activeInternal||!this.projectInternal)return s.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns([],this.interceptionHandlerBound);let e=new Set;for(const t of this.projectInternal.uiSourceCodes()){const s=this.patternForFileSystemUISourceCode(t);if(u.Runtime.experiments.isEnabled(u.Runtime.ExperimentName.HEADER_OVERRIDES)&&t.name()===_){const{headerPatterns:s,path:n,overridesWithRegex:r}=await this.generateHeaderPatterns(t);s.size>0&&(e=new Set([...e,...s]),this.#e.set(n,r))}else e.add(s);const{head:n,tail:r}=V(s);r&&e.add(n)}return s.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns(Array.from(e).map((e=>({urlPattern:e,requestStage:"Response"}))),this.interceptionHandlerBound)}async onUISourceCodeRemoved(e){await this.networkUISourceCodeRemoved(e),await this.filesystemUISourceCodeRemoved(e)}async networkUISourceCodeRemoved(e){e.project().type()===r.Workspace.projectTypes.Network&&(await this.#i(e),this.#t.delete(e),this.networkUISourceCodeForEncodedPath.delete(this.encodedPathFromUrl(e.url()))),this.#h(e)}#h(t){if(!this.projectInternal)return;const s=this.projectInternal,n=this.fileUrlFromNetworkUrl(t.url());for(let t=s.fileSystemPath().length;t<n.length;t++){if("/"!==n[t])continue;const r=e.ParsedURL.ParsedURL.concatenate(e.ParsedURL.ParsedURL.substring(n,0,t+1),".headers"),i=s.uiSourceCodeForURL(r);i&&(this.#n.add(i),this.#s.schedule(this.#y.bind(this)))}}#y(){for(const e of this.#n)this.dispatchEventToListeners(z.RequestsForHeaderOverridesFileChanged,e);return this.#n.clear(),Promise.resolve()}hasMatchingNetworkUISourceCodeForHeaderOverridesFile(t){const s=A.relativePath(t),n=e.ParsedURL.ParsedURL.slice(e.ParsedURL.ParsedURL.join(s,"/"),0,-_.length);for(const e of this.networkUISourceCodeForEncodedPath.keys())if(e.startsWith(n))return!0;return!1}async filesystemUISourceCodeRemoved(e){e.project()===this.projectInternal&&(this.updateInterceptionPatterns(),this.originalResponseContentPromises.delete(e),await this.#i(e))}async setProject(e){e!==this.projectInternal&&(this.projectInternal&&await Promise.all([...this.projectInternal.uiSourceCodes()].map((e=>this.filesystemUISourceCodeRemoved(e)))),this.projectInternal=e,this.projectInternal&&await Promise.all([...this.projectInternal.uiSourceCodes()].map((e=>this.filesystemUISourceCodeAdded(e)))),await this.updateActiveProject(),this.dispatchEventToListeners(z.ProjectChanged,this.projectInternal))}async onProjectAdded(e){if(e.type()!==r.Workspace.projectTypes.FileSystem||"overrides"!==A.fileSystemType(e))return;A.fileSystemPath(e.id())&&(this.projectInternal&&this.projectInternal.remove(),await this.setProject(e))}async onProjectRemoved(e){for(const t of e.uiSourceCodes())await this.networkUISourceCodeRemoved(t);e===this.projectInternal&&await this.setProject(null)}mergeHeaders(e,t){const n=new i.MapUtilities.Multimap;for(const{name:e,value:s}of t)"set-cookie"!==e.toLowerCase()&&n.set(e.toLowerCase(),s);const r=new Set(n.keysArray());for(const{name:t,value:s}of e){const e=t.toLowerCase();r.has(e)||"set-cookie"===e||n.set(e,s)}const o=[];for(const e of n.keysArray())for(const t of n.get(e))o.push({name:e,value:t});const a=e.filter((e=>"set-cookie"===e.name.toLowerCase()))||[],d=t.filter((e=>"set-cookie"===e.name.toLowerCase())),l=s.NetworkManager.InterceptedRequest.mergeSetCookieHeaders(a,d);return o.push(...l),o}#P(e,t,s){const n=this.#e.get(e)||[];for(const e of n){const n=this.decodeLocalPathToUrlPath(this.rawPathFromUrl(t));e.applyToRegex.test(n)&&(s=this.mergeHeaders(s,e.headers))}return s}handleHeaderInterception(t){let s=t.responseHeaders||[];const n=this.rawPathFromUrl(t.request.url).split("/");let r=i.DevToolsPath.EmptyEncodedPathString;s=this.#P(r,t.request.url,s);for(const i of n)r=e.ParsedURL.ParsedURL.concatenate(r,i,"/"),s=this.#P(r,t.request.url,s);return s}async interceptionHandler(t){const s=t.request.method;if(!this.activeInternal||"OPTIONS"===s)return;const n=this.projectInternal,r=this.fileUrlFromNetworkUrl(t.request.url),i=n.uiSourceCodeForURL(r);let o=[];if(u.Runtime.experiments.isEnabled(u.Runtime.ExperimentName.HEADER_OVERRIDES)&&(o=this.handleHeaderInterception(t)),!i&&!o.length)return;o.length||(o=t.responseHeaders||[]);let a="";if(t.responseHeaders)for(const e of t.responseHeaders)if("content-type"===e.name.toLowerCase()){a=e.value;break}if(!a){const s=e.ResourceType.resourceTypes[t.resourceType]||e.ResourceType.resourceTypes.Other;a=i?.mimeType()||"",e.ResourceType.ResourceType.fromMimeType(a)!==s&&(a=s.canonicalMimeType())}if(i){this.originalResponseContentPromises.set(i,t.responseBody().then((e=>{if(e.error||null===e.content)return null;if(e.encoded){const t=atob(e.content),s=new Uint8Array(t.length);for(let e=0;e<t.length;++e)s[e]=t.charCodeAt(e);return new TextDecoder("utf-8").decode(s)}return e.content})));const e=i.project(),s=await e.requestFileBlob(i);s&&t.continueRequestWithContent(new Blob([s],{type:a}),!1,o,!0)}else if(t.isRedirect())t.continueRequestWithContent(new Blob([],{type:a}),!0,o,!1);else{const e=await t.responseBody();!e.error&&e.content&&t.continueRequestWithContent(new Blob([e.content],{type:a}),!0,o,!1)}}}const D=new Set(["con","prn","aux","nul","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]),_=".headers";var z;function $(e){return!!(e&&"string"==typeof e.applyTo&&e.headers&&e.headers.length&&Array.isArray(e.headers))&&e.headers.every((e=>"string"==typeof e.name&&"string"==typeof e.value))}function G(e){return i.StringUtilities.escapeCharacters(e,"[]{}()\\.^$+|-,?").replaceAll("*",".*")}function V(e){const t=e.lastIndexOf("/"),s=t>=0?e.slice(t+1):e,n=t>=0?e.slice(0,t+1):"",r=new RegExp("^"+G(s)+"$");return"*"!==s&&(r.test("index.html")||r.test("index.htm")||r.test("index.php"))?{head:n,tail:s}:{head:e}}!function(e){e.ProjectChanged="ProjectChanged",e.RequestsForHeaderOverridesFileChanged="RequestsForHeaderOverridesFileChanged"}(z||(z={}));var J=Object.freeze({__proto__:null,NetworkPersistenceManager:q,HEADERS_FILENAME:_,get Events(){return z},isHeaderOverride:$,escapeRegex:G,extractDirectoryIndex:V});const Y={linkedToSourceMapS:"Linked to source map: {PH1}",linkedToS:"Linked to {PH1}"},K=a.i18n.registerUIStrings("models/persistence/PersistenceUtils.ts",Y),Q=a.i18n.getLocalizedString.bind(void 0,K);class X{static tooltipForUISourceCode(e){const t=se.instance().binding(e);return t?e===t.network?A.tooltipForUISourceCode(t.fileSystem):t.network.contentType().isFromSourceMap()?Q(Y.linkedToSourceMapS,{PH1:i.StringUtilities.trimMiddle(t.network.url(),150)}):Q(Y.linkedToS,{PH1:i.StringUtilities.trimMiddle(t.network.url(),150)}):""}static iconForUISourceCode(e){const t=se.instance().binding(e);if(t){if(!t.fileSystem.url().startsWith("file://"))return null;const e=new c.Icon.Icon;return e.data={iconName:"document",color:"var(--icon-default)",width:"16px",height:"16px"},h.Tooltip.Tooltip.install(e,X.tooltipForUISourceCode(t.network)),q.instance().project()===t.fileSystem.project()?e.classList.add("dot","purple"):e.classList.add("dot","green"),e}if(e.project().type()!==r.Workspace.projectTypes.FileSystem||!e.url().startsWith("file://"))return null;if(e.url().endsWith(_)&&q.instance().hasMatchingNetworkUISourceCodeForHeaderOverridesFile(e)){const e=new c.Icon.Icon;return e.data={iconName:"document",color:"var(--icon-default)",width:"16px",height:"16px"},e.classList.add("dot","purple"),e}const s=new c.Icon.Icon;return s.data={iconName:"document",color:"var(--icon-default)",width:"16px",height:"16px"},h.Tooltip.Tooltip.install(s,X.tooltipForUISourceCode(e)),s}}class Z extends e.ObjectWrapper.ObjectWrapper{constructor(e){super(),e.addEventListener(he.BindingCreated,this.bindingChanged,this),e.addEventListener(he.BindingRemoved,this.bindingChanged,this)}bindingChanged(e){const t=e.data;this.dispatchEventToListeners(d.Linkifier.LinkDecorator.Events.LinkIconChanged,t.network)}linkIcon(e){return X.iconForUISourceCode(e)}}var ee=Object.freeze({__proto__:null,PersistenceUtils:X,LinkDecorator:Z});let te;class se extends e.ObjectWrapper.ObjectWrapper{workspace;breakpointManager;filePathPrefixesToBindingCount;subscribedBindingEventListeners;mapping;constructor(e,t){super(),this.workspace=e,this.breakpointManager=t,this.breakpointManager.addUpdateBindingsCallback(this.#F.bind(this)),this.filePathPrefixesToBindingCount=new ne,this.subscribedBindingEventListeners=new i.MapUtilities.Multimap;const s=new Z(this);d.Linkifier.Linkifier.setLinkDecorator(s),this.mapping=new me(this.workspace,this.onStatusAdded.bind(this),this.onStatusRemoved.bind(this))}static instance(e={forceNew:null,workspace:null,breakpointManager:null}){const{forceNew:t,workspace:s,breakpointManager:n}=e;if(!te||t){if(!s||!n)throw new Error("Missing arguments for workspace");te=new se(s,n)}return te}addNetworkInterceptor(e){this.mapping.addNetworkInterceptor(e)}refreshAutomapping(){this.mapping.scheduleRemap()}async addBinding(e){await this.innerAddBinding(e)}async addBindingForTest(e){await this.innerAddBinding(e)}async removeBinding(e){await this.innerRemoveBinding(e)}async removeBindingForTest(e){await this.innerRemoveBinding(e)}#F(e){return e.project().type()!==r.Workspace.projectTypes.Network?Promise.resolve():this.mapping.computeNetworkStatus(e)}async innerAddBinding(e){re.set(e.network,e),re.set(e.fileSystem,e),e.fileSystem.forceLoadOnCheckContent(),e.network.addEventListener(r.UISourceCode.Events.WorkingCopyCommitted,this.onWorkingCopyCommitted,this),e.fileSystem.addEventListener(r.UISourceCode.Events.WorkingCopyCommitted,this.onWorkingCopyCommitted,this),e.network.addEventListener(r.UISourceCode.Events.WorkingCopyChanged,this.onWorkingCopyChanged,this),e.fileSystem.addEventListener(r.UISourceCode.Events.WorkingCopyChanged,this.onWorkingCopyChanged,this),this.filePathPrefixesToBindingCount.add(e.fileSystem.url()),await this.moveBreakpoints(e.fileSystem,e.network),console.assert(!e.fileSystem.isDirty()||!e.network.isDirty()),e.fileSystem.isDirty()?this.syncWorkingCopy(e.fileSystem):e.network.isDirty()?this.syncWorkingCopy(e.network):e.network.hasCommits()&&e.network.content()!==e.fileSystem.content()&&(e.network.setWorkingCopy(e.network.content()),this.syncWorkingCopy(e.network)),this.notifyBindingEvent(e.network),this.notifyBindingEvent(e.fileSystem),this.dispatchEventToListeners(he.BindingCreated,e)}async innerRemoveBinding(e){re.get(e.network)===e&&(console.assert(re.get(e.network)===re.get(e.fileSystem),"ERROR: inconsistent binding for networkURL "+e.network.url()),re.delete(e.network),re.delete(e.fileSystem),e.network.removeEventListener(r.UISourceCode.Events.WorkingCopyCommitted,this.onWorkingCopyCommitted,this),e.fileSystem.removeEventListener(r.UISourceCode.Events.WorkingCopyCommitted,this.onWorkingCopyCommitted,this),e.network.removeEventListener(r.UISourceCode.Events.WorkingCopyChanged,this.onWorkingCopyChanged,this),e.fileSystem.removeEventListener(r.UISourceCode.Events.WorkingCopyChanged,this.onWorkingCopyChanged,this),this.filePathPrefixesToBindingCount.remove(e.fileSystem.url()),await this.breakpointManager.copyBreakpoints(e.network,e.fileSystem),this.notifyBindingEvent(e.network),this.notifyBindingEvent(e.fileSystem),this.dispatchEventToListeners(he.BindingRemoved,e))}onStatusAdded(e){const t=new ue(e.network,e.fileSystem);return ie.set(e,t),this.innerAddBinding(t)}async onStatusRemoved(e){const t=ie.get(e);await this.innerRemoveBinding(t)}onWorkingCopyChanged(e){const t=e.data;this.syncWorkingCopy(t)}syncWorkingCopy(e){const t=re.get(e);if(!t||ae.has(t))return;const r=t.network===e?t.fileSystem:t.network;if(!e.isDirty())return ae.add(t),r.resetWorkingCopy(),ae.delete(t),void this.contentSyncedForTest();const i=n.NetworkProject.NetworkProject.targetForUISourceCode(t.network);if(i&&i.type()===s.Target.Type.Node){const t=e.workingCopy();r.requestContent().then((()=>{const e=se.rewrapNodeJSContent(r,r.workingCopy(),t);o.call(this,(()=>e))}))}else o.call(this,(()=>e.workingCopy()));function o(e){t&&ae.add(t),r.setWorkingCopyGetter(e),t&&ae.delete(t),this.contentSyncedForTest()}}onWorkingCopyCommitted(e){const t=e.data.uiSourceCode,s=e.data.content;this.syncContent(t,s,Boolean(e.data.encoded))}syncContent(e,t,r){const i=re.get(e);if(!i||oe.has(i))return;const o=i.network===e?i.fileSystem:i.network,a=n.NetworkProject.NetworkProject.targetForUISourceCode(i.network);function d(e){i&&oe.add(i),o.setContent(e,r),i&&oe.delete(i),this.contentSyncedForTest()}a&&a.type()===s.Target.Type.Node?o.requestContent().then((e=>{const s=se.rewrapNodeJSContent(o,e.content||"",t);d.call(this,s)})):d.call(this,t)}static rewrapNodeJSContent(e,t,s){return e.project().type()===r.Workspace.projectTypes.FileSystem?(s.startsWith(de)&&s.endsWith(le)&&(s=s.substring(de.length,s.length-le.length)),t.startsWith(ce)&&(s=ce+s)):(s.startsWith(ce)&&(s=s.substring(ce.length)),t.startsWith(de)&&t.endsWith(le)&&(s=de+s+le)),s}contentSyncedForTest(){}async moveBreakpoints(e,t){const s=this.breakpointManager.breakpointLocationsForUISourceCode(e).map((e=>e.breakpoint));await Promise.all(s.map((async e=>(await e.remove(!1),this.breakpointManager.setBreakpoint(t,e.lineNumber(),e.columnNumber(),e.condition(),e.enabled(),e.isLogpoint(),"RESTORED")))))}hasUnsavedCommittedChanges(e){return!this.workspace.hasResourceContentTrackingExtensions()&&(!e.project().canSetFileContent()&&(!re.has(e)&&Boolean(e.hasCommits())))}binding(e){return re.get(e)||null}subscribeForBindingEvent(e,t){this.subscribedBindingEventListeners.set(e,t)}unsubscribeFromBindingEvent(e,t){this.subscribedBindingEventListeners.delete(e,t)}notifyBindingEvent(e){if(!this.subscribedBindingEventListeners.has(e))return;const t=Array.from(this.subscribedBindingEventListeners.get(e));for(const e of t)e.call(null)}fileSystem(e){const t=this.binding(e);return t?t.fileSystem:null}network(e){const t=this.binding(e);return t?t.network:null}filePathHasBindings(e){return this.filePathPrefixesToBindingCount.hasBindingPrefix(e)}}class ne{prefixCounts;constructor(){this.prefixCounts=new Map}getPlatformCanonicalFilePath(s){return t.Platform.isWin()?e.ParsedURL.ParsedURL.toLowerCase(s):s}add(e){e=this.getPlatformCanonicalFilePath(e);let t="";for(const s of e.split("/")){t+=s+"/";const e=this.prefixCounts.get(t)||0;this.prefixCounts.set(t,e+1)}}remove(e){e=this.getPlatformCanonicalFilePath(e);let t="";for(const s of e.split("/")){t+=s+"/";const e=this.prefixCounts.get(t);1===e?this.prefixCounts.delete(t):void 0!==e&&this.prefixCounts.set(t,e-1)}}hasBindingPrefix(t){return(t=this.getPlatformCanonicalFilePath(t)).endsWith("/")||(t=e.ParsedURL.ParsedURL.concatenate(t,"/")),this.prefixCounts.has(t)}}const re=new WeakMap,ie=new WeakMap,oe=new WeakSet,ae=new WeakSet,de="(function (exports, require, module, __filename, __dirname) { ",le="\n});",ce="#!/usr/bin/env node";var he;!function(e){e.BindingCreated="BindingCreated",e.BindingRemoved="BindingRemoved"}(he||(he={}));class ue{network;fileSystem;constructor(e,t){this.network=e,this.fileSystem=t}}var pe=Object.freeze({__proto__:null,PersistenceImpl:se,NodePrefix:de,NodeSuffix:le,NodeShebang:ce,get Events(){return he},PersistenceBinding:ue});class me{workspace;onStatusAdded;onStatusRemoved;statuses;fileSystemUISourceCodes;sweepThrottler;sourceCodeToProcessingPromiseMap;sourceCodeToAutoMappingStatusMap;sourceCodeToMetadataMap;filesIndex;projectFoldersIndex;activeFoldersIndex;interceptors;constructor(t,s,n){this.workspace=t,this.onStatusAdded=s,this.onStatusRemoved=n,this.statuses=new Set,this.fileSystemUISourceCodes=new Se,this.sweepThrottler=new e.Throttler.Throttler(100),this.sourceCodeToProcessingPromiseMap=new WeakMap,this.sourceCodeToAutoMappingStatusMap=new WeakMap,this.sourceCodeToMetadataMap=new WeakMap,this.filesIndex=new ge,this.projectFoldersIndex=new fe,this.activeFoldersIndex=new fe,this.interceptors=[],this.workspace.addEventListener(r.Workspace.Events.UISourceCodeAdded,(e=>this.onUISourceCodeAdded(e.data))),this.workspace.addEventListener(r.Workspace.Events.UISourceCodeRemoved,(e=>this.onUISourceCodeRemoved(e.data))),this.workspace.addEventListener(r.Workspace.Events.UISourceCodeRenamed,this.onUISourceCodeRenamed,this),this.workspace.addEventListener(r.Workspace.Events.ProjectAdded,(e=>this.onProjectAdded(e.data)),this),this.workspace.addEventListener(r.Workspace.Events.ProjectRemoved,(e=>this.onProjectRemoved(e.data)),this);for(const e of t.projects())this.onProjectAdded(e);for(const e of t.uiSourceCodes())this.onUISourceCodeAdded(e)}addNetworkInterceptor(e){this.interceptors.push(e),this.scheduleRemap()}scheduleRemap(){for(const e of this.statuses.values())this.clearNetworkStatus(e.network);this.scheduleSweep()}scheduleSweep(){this.sweepThrottler.schedule(function(){const e=this.workspace.projectsForType(r.Workspace.projectTypes.Network);for(const t of e)for(const e of t.uiSourceCodes())this.computeNetworkStatus(e);return this.onSweepHappenedForTest(),Promise.resolve()}.bind(this))}onSweepHappenedForTest(){}onProjectRemoved(e){for(const t of e.uiSourceCodes())this.onUISourceCodeRemoved(t);if(e.type()!==r.Workspace.projectTypes.FileSystem)return;const t=e;for(const e of t.initialGitFolders())this.projectFoldersIndex.removeFolder(e);this.projectFoldersIndex.removeFolder(t.fileSystemPath()),this.scheduleRemap()}onProjectAdded(e){if(e.type()!==r.Workspace.projectTypes.FileSystem)return;const t=e;for(const e of t.initialGitFolders())this.projectFoldersIndex.addFolder(e);this.projectFoldersIndex.addFolder(t.fileSystemPath());for(const t of e.uiSourceCodes())this.onUISourceCodeAdded(t);this.scheduleRemap()}onUISourceCodeAdded(e){const t=e.project();if(t.type()===r.Workspace.projectTypes.FileSystem){if(!A.fileSystemSupportsAutomapping(t))return;this.filesIndex.addPath(e.url()),this.fileSystemUISourceCodes.add(e),this.scheduleSweep()}else t.type()===r.Workspace.projectTypes.Network&&this.computeNetworkStatus(e)}onUISourceCodeRemoved(e){if(e.project().type()===r.Workspace.projectTypes.FileSystem){this.filesIndex.removePath(e.url()),this.fileSystemUISourceCodes.delete(e.url());const t=this.sourceCodeToAutoMappingStatusMap.get(e);t&&this.clearNetworkStatus(t.network)}else e.project().type()===r.Workspace.projectTypes.Network&&this.clearNetworkStatus(e)}onUISourceCodeRenamed(e){const{uiSourceCode:t,oldURL:s}=e.data;if(t.project().type()!==r.Workspace.projectTypes.FileSystem)return;this.filesIndex.removePath(s),this.fileSystemUISourceCodes.delete(s);const n=this.sourceCodeToAutoMappingStatusMap.get(t);n&&this.clearNetworkStatus(n.network),this.filesIndex.addPath(t.url()),this.fileSystemUISourceCodes.add(t),this.scheduleSweep()}computeNetworkStatus(e){const t=this.sourceCodeToProcessingPromiseMap.get(e);if(t)return t;if(this.sourceCodeToAutoMappingStatusMap.has(e))return Promise.resolve();if(this.interceptors.some((t=>t(e))))return Promise.resolve();if(e.url().startsWith("wasm://"))return Promise.resolve();const r=this.createBinding(e).then(async function(t){if(!t)return null;if(this.sourceCodeToProcessingPromiseMap.get(e)!==r)return null;if(t.network.contentType().isFromSourceMap()||!t.fileSystem.contentType().isTextType())return t;if(t.fileSystem.isDirty()&&(t.network.isDirty()||t.network.hasCommits()))return null;const[i,o]=await Promise.all([t.fileSystem.requestContent(),t.network.project().requestFileContent(t.network)]);if(null===i.content||null===o)return null;if(this.sourceCodeToProcessingPromiseMap.get(e)!==r)return null;const a=n.NetworkProject.NetworkProject.targetForUISourceCode(t.network);let d=!1;const l=i.content;if(a&&a.type()===s.Target.Type.Node){if(o.content){const e=se.rewrapNodeJSContent(t.fileSystem,l,o.content);d=l===e}}else o.content&&(d=l.trimEnd()===o.content.trimEnd());if(!d)return this.prevalidationFailedForTest(t),null;return t}.bind(this)).then(async function(t){if(this.sourceCodeToProcessingPromiseMap.get(e)!==r)return;if(!t)return this.onBindingFailedForTest(),void this.sourceCodeToProcessingPromiseMap.delete(e);if(this.sourceCodeToAutoMappingStatusMap.has(t.network)||this.sourceCodeToAutoMappingStatusMap.has(t.fileSystem))return void this.sourceCodeToProcessingPromiseMap.delete(e);if(this.statuses.add(t),this.sourceCodeToAutoMappingStatusMap.set(t.network,t),this.sourceCodeToAutoMappingStatusMap.set(t.fileSystem,t),t.exactMatch){const e=this.projectFoldersIndex.closestParentFolder(t.fileSystem.url());!!e&&this.activeFoldersIndex.addFolder(e)&&this.scheduleSweep()}await this.onStatusAdded.call(null,t),this.sourceCodeToProcessingPromiseMap.delete(e)}.bind(this));return this.sourceCodeToProcessingPromiseMap.set(e,r),r}prevalidationFailedForTest(e){}onBindingFailedForTest(){}clearNetworkStatus(e){if(this.sourceCodeToProcessingPromiseMap.has(e))return void this.sourceCodeToProcessingPromiseMap.delete(e);const t=this.sourceCodeToAutoMappingStatusMap.get(e);if(t){if(this.statuses.delete(t),this.sourceCodeToAutoMappingStatusMap.delete(t.network),this.sourceCodeToAutoMappingStatusMap.delete(t.fileSystem),t.exactMatch){const e=this.projectFoldersIndex.closestParentFolder(t.fileSystem.url());e&&this.activeFoldersIndex.removeFolder(e)}this.onStatusRemoved.call(null,t)}}async createBinding(t){const s=t.url();if(s.startsWith("file://")||s.startsWith("snippet://")){const e=this.fileSystemUISourceCodes.get(s);return e?new ye(t,e,!1):null}let n=e.ParsedURL.ParsedURL.extractPath(s);if(null===n)return null;n.endsWith("/")&&(n=e.ParsedURL.ParsedURL.concatenate(n,"index.html"));const r=this.filesIndex.similarFiles(n).map((e=>this.fileSystemUISourceCodes.get(e)));if(!r.length)return null;await Promise.all(r.concat(t).map((async e=>{this.sourceCodeToMetadataMap.set(e,await e.requestMetadata())})));const i=r.filter((e=>Boolean(this.activeFoldersIndex.closestParentFolder(e.url())))),o=this.sourceCodeToMetadataMap.get(t);if(!o||!o.modificationTime&&"number"!=typeof o.contentSize)return 1!==i.length?null:new ye(t,i[0],!1);let a=this.filterWithMetadata(i,o);return a.length||(a=this.filterWithMetadata(r,o)),1!==a.length?null:new ye(t,a[0],!0)}filterWithMetadata(e,t){return e.filter((e=>{const s=this.sourceCodeToMetadataMap.get(e);if(!s)return!1;const n=!t.modificationTime||!s.modificationTime||Math.abs(t.modificationTime.getTime()-s.modificationTime.getTime())<1e3,r=!t.contentSize||s.contentSize===t.contentSize;return n&&r}))}}class ge{#w=e.Trie.Trie.newArrayTrie();addPath(e){const t=e.split("/").reverse();this.#w.add(t)}removePath(e){const t=e.split("/").reverse();this.#w.remove(t)}similarFiles(e){const t=e.split("/").reverse(),s=this.#w.longestPrefix(t,!1);return 0===s.length?[]:this.#w.words(s).map((e=>e.reverse().join("/")))}}class fe{#v=e.Trie.Trie.newArrayTrie();#C=new Map;addFolder(e){const t=this.#I(e).split("/");this.#v.add(t);const s=t.join("/"),n=this.#C.get(s)??0;return this.#C.set(s,n+1),0===n}removeFolder(e){const t=this.#I(e).split("/"),s=t.join("/"),n=this.#C.get(s)??0;return!!n&&(n>1?(this.#C.set(s,n-1),!1):(this.#v.remove(t),this.#C.delete(s),!0))}closestParentFolder(e){const t=e.split("/");return this.#v.longestPrefix(t,!0).join("/")}#I(t){return t.endsWith("/")?e.ParsedURL.ParsedURL.substring(t,0,t.length-1):t}}class Se{sourceCodes;constructor(){this.sourceCodes=new Map}getPlatformCanonicalFileUrl(s){return t.Platform.isWin()?e.ParsedURL.ParsedURL.toLowerCase(s):s}add(e){const t=this.getPlatformCanonicalFileUrl(e.url());this.sourceCodes.set(t,e)}get(e){return e=this.getPlatformCanonicalFileUrl(e),this.sourceCodes.get(e)}delete(e){e=this.getPlatformCanonicalFileUrl(e),this.sourceCodes.delete(e)}}class ye{network;fileSystem;exactMatch;constructor(e,t,s){this.network=e,this.fileSystem=t,this.exactMatch=s}}var Pe=Object.freeze({__proto__:null,Automapping:me,AutomappingStatus:ye});const Fe=new CSSStyleSheet;Fe.replaceSync(".file-system-header{display:flex;flex-direction:row;align-items:center;flex:auto;margin:10px 0}.file-system-header-text{flex:1 0 auto}.add-button{margin-left:10px;align-self:flex-start}.file-system-list{flex:auto}.file-system-list-empty{flex:auto;height:30px;display:flex;align-items:center;justify-content:center;text-align:center}.file-system-list-item{padding:3px 5px;height:30px;display:flex;align-items:center;flex:auto 1 1}.file-system-value{flex:1 1 0}.list-item .file-system-value{white-space:nowrap;text-overflow:ellipsis;user-select:none;overflow:hidden}.file-system-edit-row{flex:none;display:flex;flex-direction:row;margin:6px 5px;align-items:center}.file-system-edit-row input{width:100%;text-align:inherit}\n/*# sourceURL=editFileSystemView.css */\n");const we={excludedFolders:"Excluded folders",add:"Add",none:"None",sViaDevtools:"{PH1} (via .devtools)",folderPath:"Folder path",enterAPath:"Enter a path",enterAUniquePath:"Enter a unique path"},ve=a.i18n.registerUIStrings("models/persistence/EditFileSystemView.ts",we),Ce=a.i18n.getLocalizedString.bind(void 0,ve);class Ie extends h.Widget.VBox{fileSystemPath;excludedFolders;eventListeners;excludedFoldersList;muteUpdate;excludedFolderEditor;constructor(e){super(!0),this.fileSystemPath=e,this.excludedFolders=[],this.eventListeners=[T.instance().addEventListener(M.ExcludedFolderAdded,this.update,this),T.instance().addEventListener(M.ExcludedFolderRemoved,this.update,this)];const t=this.contentElement.createChild("div","file-system-header");t.createChild("div","file-system-header-text").textContent=Ce(we.excludedFolders),t.appendChild(h.UIUtils.createTextButton(Ce(we.add),this.addExcludedFolderButtonClicked.bind(this),"add-button")),this.excludedFoldersList=new h.ListWidget.ListWidget(this),this.excludedFoldersList.element.classList.add("file-system-list");const s=document.createElement("div");s.classList.add("file-system-list-empty"),s.textContent=Ce(we.none),this.excludedFoldersList.setEmptyPlaceholder(s),this.excludedFoldersList.show(this.contentElement),this.update()}dispose(){e.EventTarget.removeEventListeners(this.eventListeners)}getFileSystem(){return T.instance().fileSystem(this.fileSystemPath)}update(){if(!this.muteUpdate){this.excludedFoldersList.clear(),this.excludedFolders=[];for(const e of this.getFileSystem().excludedFolders().values())this.excludedFolders.push(e),this.excludedFoldersList.appendItem(e,!0)}}addExcludedFolderButtonClicked(){this.excludedFoldersList.addNewItem(0,"")}renderItem(e,t){const s=document.createElement("div");s.classList.add("file-system-list-item");const n=t?e:Ce(we.sViaDevtools,{PH1:e}),r=s.createChild("div","file-system-value");return r.textContent=n,h.Tooltip.Tooltip.install(r,n),s}removeItemRequested(e,t){this.getFileSystem().removeExcludedFolder(this.excludedFolders[t])}commitEdit(e,t,s){this.muteUpdate=!0,s||this.getFileSystem().removeExcludedFolder(e),this.getFileSystem().addExcludedFolder(this.normalizePrefix(t.control("pathPrefix").value)),this.muteUpdate=!1,this.update()}beginEdit(e){const t=this.createExcludedFolderEditor();return t.control("pathPrefix").value=e,t}createExcludedFolderEditor(){if(this.excludedFolderEditor)return this.excludedFolderEditor;const e=new h.ListWidget.Editor;this.excludedFolderEditor=e;const t=e.contentElement();t.createChild("div","file-system-edit-row").createChild("div","file-system-value").textContent=Ce(we.folderPath);return t.createChild("div","file-system-edit-row").createChild("div","file-system-value").appendChild(e.createInput("pathPrefix","text","/path/to/folder/",function(e,t,s){const n=this.normalizePrefix(s.value.trim());if(!n)return{valid:!1,errorMessage:Ce(we.enterAPath)};const r=this.getFileSystem().excludedFolders().size;for(let e=0;e<r;++e)if(e!==t&&this.excludedFolders[e]===n)return{valid:!1,errorMessage:Ce(we.enterAUniquePath)};return{valid:!0,errorMessage:void 0}}.bind(this))),e}normalizePrefix(e){return e?e+("/"===e[e.length-1]?"":"/"):""}wasShown(){super.wasShown(),this.excludedFoldersList.registerCSSFiles([Fe]),this.registerCSSFiles([Fe])}}var Ue=Object.freeze({__proto__:null,EditFileSystemView:Ie});const ke={saveAs:"Save as...",saveImage:"Save image",saveForOverrides:"Save for overrides",openInContainingFolder:"Open in containing folder"},Re=a.i18n.registerUIStrings("models/persistence/PersistenceActions.ts",ke),xe=a.i18n.getLocalizedString.bind(void 0,Re);let Le;class be{static instance(e={forceNew:null}){const{forceNew:t}=e;return Le&&!t||(Le=new be),Le}appendApplicableItems(n,i,o){const a=o;a.contentType().isDocumentOrScriptOrStyleSheet()?i.saveSection().appendItem(xe(ke.saveAs),(async function(){a instanceof r.UISourceCode.UISourceCode&&a.commitWorkingCopy();const e=await a.requestContent();let t=e.content||"";e.isEncoded&&(t=window.atob(t));const s=a.contentURL();r.FileManager.FileManager.instance().save(s,t,!0),r.FileManager.FileManager.instance().close(s)})):a instanceof s.Resource.Resource&&a.contentType().isImage()&&i.saveSection().appendItem(xe(ke.saveImage),(async function(){const e=a,t=(await e.requestContent()).content||"",s=document.createElement("a");s.download=e.displayName,s.href="data:"+e.mimeType+";base64,"+t,s.click()}));const d=r.Workspace.WorkspaceImpl.instance().uiSourceCodeForURL(a.contentURL());d&&q.instance().canSaveUISourceCodeForOverrides(d)&&i.saveSection().appendItem(xe(ke.saveForOverrides),(()=>{d.commitWorkingCopy(),q.instance().saveUISourceCodeForOverrides(d),e.Revealer.reveal(d)}));const l=d&&se.instance().binding(d),c=l?l.fileSystem.contentURL():a.contentURL();if(c.startsWith("file://")){const s=e.ParsedURL.ParsedURL.urlToRawPathString(c,t.Platform.isWin());i.revealSection().appendItem(xe(ke.openInContainingFolder),(()=>t.InspectorFrontendHost.InspectorFrontendHostInstance.showItemInFolder(s)))}}}var Ee=Object.freeze({__proto__:null,ContextMenuProvider:be});const Te=new CSSStyleSheet;Te.replaceSync('.workspace-settings-tab header{padding:0 0 6px}.workspace-settings-tab header > h1{font-size:18px;font-weight:normal;margin:0;padding-bottom:3px}.workspace-settings-tab .settings-content{overflow-y:auto;overflow-x:hidden;margin:8px 8px 8px 0;padding:0 4px;flex:auto}.workspace-settings-tab .settings-container{width:100%;column-width:288px}.workspace-settings-tab .settings-tab.settings-container{column-width:308px}.workspace-settings-tab .settings-container-wrapper{position:absolute;top:31px;left:0;right:0;bottom:0;overflow:auto;padding-top:9px}.workspace-settings-tab .settings-tab.settings-content{margin:0;padding:0}.workspace-settings-tab .settings-tab p{margin:12px 0}.workspace-settings-tab p.folder-exclude-pattern{display:grid;align-items:center}.workspace-settings-tab p.folder-exclude-pattern > input{width:80%;margin-left:10px}.workspace-settings-tab .settings-tab .file-system-container{border-top:1px solid var(--color-background-elevation-2);padding:19px 0 10px;margin:20px 0}.workspace-settings-tab .settings-tab .file-system-header{display:flex;flex-direction:row;align-items:center}.workspace-settings-tab .settings-tab .file-system-name{font-weight:bold;flex:none;margin-right:10px;font-size:15px;overflow:hidden;text-overflow:ellipsis;max-width:70%}.workspace-settings-tab .settings-tab .file-system-path{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:auto}.workspace-settings-tab .settings-info-message{background-color:var(--color-background-elevation-1);padding:10px;margin:20px 0}.workspace-settings-tab .settings-tab.settings-content.settings-container{column-width:initial;overflow:hidden;padding-right:10px}.workspace-settings-tab .harmony-input[type="text"]:not(.error-input):not(:invalid){box-shadow:var(--legacy-focus-ring-inactive-shadow)}\n/*# sourceURL=workspaceSettingsTab.css */\n');const Me={workspace:"Workspace",mappingsAreInferredAutomatically:"Mappings are inferred automatically.",addFolder:"Add folder…",folderExcludePattern:"Folder exclude pattern",remove:"Remove"},je=a.i18n.registerUIStrings("models/persistence/WorkspaceSettingsTab.ts",Me),We=a.i18n.getLocalizedString.bind(void 0,je);let Ae;class Be extends h.Widget.VBox{containerElement;fileSystemsListContainer;elementByPath;mappingViewByPath;constructor(){super(),this.element.classList.add("workspace-settings-tab");const e=this.element.createChild("header");h.UIUtils.createTextChild(e.createChild("h1"),We(Me.workspace)),this.containerElement=this.element.createChild("div","settings-container-wrapper").createChild("div","settings-tab settings-content settings-container"),T.instance().addEventListener(M.FileSystemAdded,(e=>this.fileSystemAdded(e.data)),this),T.instance().addEventListener(M.FileSystemRemoved,(e=>this.fileSystemRemoved(e.data)),this);const t=this.createFolderExcludePatternInput();t.classList.add("folder-exclude-pattern"),this.containerElement.appendChild(t);const s=this.containerElement.createChild("div","settings-info-message");h.UIUtils.createTextChild(s,We(Me.mappingsAreInferredAutomatically)),this.fileSystemsListContainer=this.containerElement.createChild("div","");const n=h.UIUtils.createTextButton(We(Me.addFolder),this.addFileSystemClicked.bind(this));this.containerElement.appendChild(n),this.setDefaultFocusedElement(n),this.elementByPath=new Map,this.mappingViewByPath=new Map;const r=T.instance().fileSystems();for(let e=0;e<r.length;++e)this.addItem(r[e])}static instance(e={forceNew:null}){const{forceNew:t}=e;return Ae&&!t||(Ae=new Be),Ae}wasShown(){super.wasShown(),this.registerCSSFiles([Te])}createFolderExcludePatternInput(){const e=document.createElement("p"),t=e.createChild("label");t.textContent=We(Me.folderExcludePattern);const s=h.UIUtils.createInput("","text");h.ARIAUtils.bindLabelToControl(t,s),e.appendChild(s);const n=T.instance().workspaceFolderExcludePatternSetting(),r=h.UIUtils.bindInput(s,n.set.bind(n),(function(e){let t;try{t=new RegExp(e)}catch(e){}return{valid:Boolean(t),errorMessage:void 0}}),!1);return n.addChangeListener((()=>r.call(null,n.get()))),r(n.get()),e}addItem(e){if(!(e instanceof w))return;const t=q.instance().project();if(t&&T.instance().fileSystem(t.fileSystemPath())===e)return;const s=this.renderFileSystem(e);this.elementByPath.set(e.path(),s),this.fileSystemsListContainer.appendChild(s);const n=new Ie(e.path());this.mappingViewByPath.set(e.path(),n),n.element.classList.add("file-system-mapping-view"),n.show(s)}renderFileSystem(e){const t=e.path(),s=t.lastIndexOf("/"),n=t.substr(s+1),r=document.createElement("div");r.classList.add("file-system-container");const i=r.createChild("div","file-system-header"),o=i.createChild("div","file-system-name");o.textContent=n,h.ARIAUtils.markAsHeading(o,2);const a=i.createChild("div","file-system-path");a.textContent=t,h.Tooltip.Tooltip.install(a,t);const d=new h.Toolbar.Toolbar(""),l=new h.Toolbar.ToolbarButton(We(Me.remove),"cross");return l.addEventListener(h.Toolbar.ToolbarButton.Events.Click,this.removeFileSystemClicked.bind(this,e)),d.appendToolbarItem(l),i.appendChild(d.element),r}removeFileSystemClicked(e){T.instance().removeFileSystem(e)}addFileSystemClicked(){T.instance().addFileSystem()}fileSystemAdded(e){this.addItem(e)}fileSystemRemoved(e){const t=this.mappingViewByPath.get(e.path());t&&(t.dispose(),this.mappingViewByPath.delete(e.path()));const s=this.elementByPath.get(e.path());s&&(this.elementByPath.delete(e.path()),s.remove())}}var He=Object.freeze({__proto__:null,WorkspaceSettingsTab:Be});export{Pe as Automapping,Ue as EditFileSystemView,N as FileSystemWorkspaceBinding,R as IsolatedFileSystem,W as IsolatedFileSystemManager,J as NetworkPersistenceManager,pe as Persistence,Ee as PersistenceActions,ee as PersistenceUtils,S as PlatformFileSystem,He as WorkspaceSettingsTab};
